import java.io.*;
import java.net.*;
import java.util.concurrent.ArrayBlockingQueue;


public class MyClientSocket {
	
	private int queueSize = 2; //Size of the incoming and outgoing message handler queues
	private InetAddress ip;
	private int port;
	private int socketPort;
	private IMHT incoming;
	private OMHT outgoing;
	String connectSuccess = "Win";
	InetAddress myIP = InetAddress.getLocalHost();
	private ArrayBlockingQueue<DatagramPacket> inQueue;
	private ArrayBlockingQueue<DatagramPacket> outQueue;
	
	public MyClientSocket(String ip, int port) throws UnknownHostException{
		
		
		this.ip = InetAddress.getByName(ip);
		this.port = port;
		
		//start queues and pass to message handlers
		
		inQueue = new ArrayBlockingQueue<DatagramPacket>(queueSize);
		outQueue = new ArrayBlockingQueue<DatagramPacket>(queueSize);
		
		incoming = new IMHT(inQueue);
		outgoing = new OMHT(outQueue);
		
		String toSend = ip + ":" + myIP.toString() + ":0**0";
		send(toSend.getBytes());
		String MSGBack = receive().toString();
		
		if (MSGBack != "0"){
			System.out.print("Connection succeeded.\n");
			setSocketPort(MSGBack);
		}else{
			System.out.print("Connection Failed.\n");
			
		}
		
		
	}

	
	private void setSocketPort(String port) {
		this.socketPort = Integer.parseInt(port);
		
	}
	
	public int getSocketPort(){
		return socketPort;
		
	}


	public byte[] receive(){
		byte[] bytes;
		DatagramPacket packet = inQueue.poll();
		
		if (packet != null){
		bytes = packet.getData();
		return bytes;
		}else{
			return null;
		}
		
		
	}

	public void send(byte[] bytes) {
		
		DatagramPacket packet = new DatagramPacket(bytes, bytes.length, ip, port);
		outQueue.add(packet);

	}
	
	public void close() {
		String toSend = ip + ":" + myIP.toString() + ":0**4";
		send(toSend.getBytes());
		String returnMSG = receive().toString();
		System.out.print( returnMSG + "\n");
		
	}
}
